Chatroom โ€” WebSocket endpoints + per-room Pub/Sub

The core question: how do the "client โ†’ WS server" half and the "chat service โ†’ Pub/Sub" half join into one system? Answer: they form a loop, not a line.

Architecture

Chatroom architecture with WebSocket endpoints and per-room Pub/Sub Client Alice / Bob Load Balancer sticky routing WebSocket servers hold open connections WS-1 (Alice) WS-2 (Bob) WS-3 โ€ฆ Chat Service validate ยท persist ยท publish Message DB chat history Pub/Sub topic per room:{id} 1 WS frame 2 3 RPC: send 4 persist 5 publish room:42 6 fan-out to subscribers 7 push Inbound: send a message (1โ†’5) Outbound: fan-out to room members (6โ†’7)

The loop, step by step

Inbound โ€” Alice sends "hi" to room 42

  1. Alice's phone sends the frame over her open WebSocket to the server she's pinned to (WS-1).
  2. LB routed her there originally (sticky, so the long-lived connection stays put).
  3. WS-1 makes an RPC to the Chat Service. This is the connection the two halves share.
  4. Chat Service validates, then persists to the Message DB (history).
  5. Chat Service publishes to Pub/Sub topic room:42.

Outbound โ€” Bob (room 42) is on a different server WS-2

  1. Every endpoint server holding a member of room 42 is subscribed to room:42. Pub/Sub fans the message out to all of them, including WS-2.
  2. WS-2 pushes the frame down Bob's WebSocket.

The sender's server never needs to know where the other members are connected. That's the whole reason Pub/Sub sits in the middle.

Two corrections to watch for: the client pushes to its WS server, not to Pub/Sub. And the WS server receives updates from Pub/Sub, not directly from the Chat Service. The Chat Service publishes; WS servers subscribe.

Why each piece is there

Follow-ups an interviewer will hit